package main

import (
	"dssh/common"
	"dssh/endpoint"
	"dssh/service"
	"dssh/transport"
	"flag"
	"fmt"
	"gitee.com/dingyangzhuang/dingutils/dlog"
	"gitee.com/dingyangzhuang/dingutils/dlog/logger"
	"gitee.com/dingyangzhuang/dingutils/dnacos"
	"gitee.com/dingyangzhuang/dingutils/ip"
	httpTransport "github.com/go-kit/kit/transport/http"
	"github.com/gorilla/mux"
	"gopkg.in/yaml.v3"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"syscall"
)

func main() {
	var (
		NacosIp     = flag.String("nacos.addr", "10.114.102.164", "nacos address")
		NacosPort   = flag.Int("nacos.port", 8848, "nacos port")
		NAMESPACEID = flag.String("nachos.namespaceid", "3c1d748d-c974-4a1b-8ad6-49eea9564da2", "nacos NAMESPACEID")
		DATAID      = flag.String("nacos.dataid", "dssh.yml", "nacos DATAID")
		GROUP       = flag.String("nacos.group", "DEFAULT_GROUP", "nacos GROUP")
		LEVEL       = flag.String("nacos.level", "info", "nacos.level")
	)
	flag.Parse()
	//初始化日志
	initLogger(*LEVEL)
	common.InitLog()

	// Logging domain.
	//var logger log.Logger
	//{
	//	logger = log.NewLogfmtLogger(os.Stderr)
	//	logger = log.With(logger, "ts", log.DefaultTimestampUTC)
	//	logger = log.With(logger, "caller", log.DefaultCaller)
	//}

	client := dnacos.NewNacosConfigClient[common.NacosConfig](*NacosIp, uint64(*NacosPort), *NAMESPACEID, *LEVEL)
	fmt.Println("***************************************")

	config := common.NacosConfig{}
	client.ReadConfigFromYml(*DATAID, *GROUP, &config)
	fmt.Printf("%+v\n", config)

	//初始化
	common.InitConstat(config)

	// 注册配置监听器
	client.NaconfigListen(*DATAID, *GROUP, func(namespace, group, dataId, data string) {
		fmt.Printf("配置变化了，新的配置内容为: %s\n", data)
		err := yaml.Unmarshal([]byte(data), &config)
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		common.InitConstat(config)
		fmt.Println(config)
	})

	//注册服务
	serverPort, err := strconv.Atoi(config.NacosServer.ServerPort)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	weight, err := strconv.Atoi(config.NacosServer.Weight)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	client.RegisterServiceInstance(ip.GetHostIpFromUDP(), serverPort,
		config.NacosServer.ServerName, weight, config.NacosServer.ClusterName, config.NacosServer.Group)

	//自定义命令调用
	//ctx := context.Background()
	r := mux.NewRouter()
	custom := service.CustomService{}
	endPoint := endpoint.GetCustomEndPoint(custom)
	r.PathPrefix("/custom").
		Handler(httpTransport.NewServer(endPoint, transport.DecodeCustomRequest, transport.EncodeCunstomResponse))

	// Interrupt handler.
	errc := make(chan error)
	go func() {
		c := make(chan os.Signal)
		signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
		errc <- fmt.Errorf("%s", <-c)
	}()

	// HTTP transport.
	go func() {
		logger.Info("transport", "method", "HTTP", "addr", config.NacosServer.ServerPort)
		errc <- http.ListenAndServe(":"+config.NacosServer.ServerPort, r)
	}()

	// Run!
	logger.Info("exit", "msg", <-errc)
}

func initLogger(level string) {

	switch level {
	case "debug":
		dlog.SetFileJsonLogger("./log/app.log", false, slog.LevelDebug, nil)
	case "info":
		dlog.SetFileJsonLogger("./log/app.log", false, slog.LevelInfo, nil)
	case "error":
		dlog.SetFileJsonLogger("./log/app.log", false, slog.LevelError, nil)
	case "warn":
		dlog.SetFileJsonLogger("./log/app.log", false, slog.LevelWarn, nil)
	}
}
